﻿using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QiAdmin.Core.Services.Log.NLog
{
    public class NLogService : ILogService
    {
        readonly string ConfigPath = AppDomain.CurrentDomain.BaseDirectory + "Services/Log/NLog/NLog.config";
        readonly Logger _logger;
        public NLogService() {
            if (!File.Exists(ConfigPath))
            {
                throw new SystemException("未找到NLog配置文件:" + ConfigPath);
            }
            LogManager.Setup().LoadConfigurationFromFile(ConfigPath);
            _logger = LogManager.GetCurrentClassLogger();
        }

        /// <summary>
        /// 获取日志详情
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        private string GetLogMsg(string msg)
        {
            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace.GetFrame(2);
            string message = $"\r\n【Action】{stackFrame.GetMethod().Name}\r\n【Detail】{msg}";
            return message;
        }

        public void Debug(string msg, Exception exception = null)
        {
            if (_logger.IsDebugEnabled)
            {
                string message = GetLogMsg(msg);
                _logger.Debug(exception == null ? message : $"{message}\r\n【Exception】", exception);
            }
        }

        public void Error(string msg, Exception exception = null)
        {
            if (_logger.IsErrorEnabled)
            {
                string message = GetLogMsg(msg);
                _logger.Error(exception == null ? message : $"{message}\r\n【Exception】", exception);
            }
        }

        public void Fatal(string msg, Exception exception = null)
        {
            if (_logger.IsFatalEnabled)
            {
                string message = GetLogMsg(msg);
                _logger.Fatal(exception == null ? message : $"{message}\r\n【Exception】", exception);
            }
        }

        public void Info(string msg, Exception exception = null)
        {
            if (_logger.IsInfoEnabled)
            {
                string message = GetLogMsg(msg);
                _logger.Info(exception == null ? message : $"{message}\r\n【Exception】", exception);
            }
        }

        public void Warn(string msg, Exception exception = null)
        {
            if (_logger.IsWarnEnabled)
            {
                string message = GetLogMsg(msg);
                _logger.Warn(exception == null ? message : $"{message}\r\n【Exception】", exception);
            }
        }
    }
}
